package servlets;

import java.io.IOException;
//import java.io.PrintWriter;
import java.util.Properties;
import java.util.Vector;

import javax.ejb.EJB;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.itextpdf.text.Document;
import com.sun.xml.ws.runtime.dev.Session;

import service.CandidateService;
import service.DepartmentService;
import service.PositionDescriptionService;
import service.PositionService;
import service.UserService;
import entityJPA.Candidate;
import entityJPA.Department;
import entityJPA.Position;
import entityJPA.Positiondescription;
import entityJPA.Positionstatus;
import entityJPA.User;

/**
 * Servlet implementation class PositionServiceServlet
 */
@WebServlet(name = "PositionServiceServlet", urlPatterns = {
		"/PositionServiceServlet", "/addPosition",
"/positionPages/PositionServiceServlet" })
public class PositionServiceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	private PositionService positionService;
	// @EJB PositionCommentService positionCommentService;
	@EJB
	private PositionDescriptionService posDescService;
	@EJB
	private CandidateService candService;
	@EJB
	private DepartmentService dService;
	
	private int indexActive = 0;
	private int indexInactive = 0;
	
	private int displace = 3;
	
	// @EJB UserService userService;


	@EJB
	private UserService userService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PositionServiceServlet() {
		super();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getSession().setAttribute("operationIsSuccesful", "");

		if (request.getParameter("insert") != null) {
			add(request, response);
		} else if (request.getParameter("update") != null) {
			edit(request, response);
		} else if (request.getParameter("remove") != null) {
			delete(request, response);
		} else if(request.getParameter("sendEmail") != null){

			String userName =(String) request.getSession().getAttribute("savedUserName");
			User u=userService.getUserByUserName(userName);
			String mail = u.getEmail();

			String body = "Position name: " + request.getParameter("name")
					+ ", number of persons" + request.getParameter("nrPersons")
					+ ", project" + request.getParameter("project")
					+ ", department" + request.getParameter("department")
					+ ", requirements" + request.getParameter("requirements")
					+ ", responsbilities"
					+ request.getParameter("responsabilities");
			String details = request.getParameter("details");
			if (request.getParameter("expType").equalsIgnoreCase("2")){
				Position p = new Position();
				p.setIdPosition(Integer.parseInt(request.getParameter("idPosition")));
				Vector<Candidate> vector = candService.getCandidatesForPosition(p);
				for (Candidate candidate : vector) {
					body+= candidate.toString() + "\n";
				}

			}

			sendMail(mail, "Position description", body);

		}


		else if (request.getParameter("activate") != null) {
			activate(request, response);
		}

		
		if (request.getParameter("nextActive") != null) {
			if (indexActive + displace >= positionService.getTotalActive()) {
				indexActive = 0;
			} else {
				indexActive += displace;
			}
		} else if (request.getParameter("previousActive") != null) {
			if (indexActive - displace < 0) {
				indexActive = 0;
			} else {
				indexActive -= displace;
			}
			
		}
		if (request.getParameter("nextInactive") != null) {
				if (indexInactive + displace >= positionService.getTotalInactive()) {
					indexInactive = 0;
				} else {
					indexInactive += displace;
				}
		} else if (request.getParameter("previousInactive") != null) {
				if (indexInactive - displace < 0) {
					indexInactive = 0;
				} else {
					indexInactive -= displace;
				}

		}
		try {
			request.setAttribute("allPositions",
					positionService.getPositionPageActive(indexActive, displace));
		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
		try {
			request.setAttribute("allInactivePositions",
					positionService.getPositionPageInactive(indexInactive, displace));
		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}


		request.setAttribute("dep", dService.getAllDepartments());
		request.getRequestDispatcher("./addPosition.jsp").forward(request,
				response);
	}

	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String link = request.getRequestURL().toString();
		
		String name = request.getParameter("name");
		int nrPersons = Integer.parseInt(request.getParameter("nrPersons"));
		String userName =(String) request.getSession().getAttribute("savedUserName");
		User u1=userService.getUserByUserName(userName);
		Position pos = new Position();
		pos.setIdUser(u1.getIdUser());
		pos.setName(name);
		pos.setNrPersons(nrPersons);
		Positiondescription pd = new Positiondescription();
		pd.setIdPositionDescription(addDesc(request, response));
		pos.setPositiondescription(pd);
		Positionstatus ps = positionService.getPositionSatusByValue("inactive");
		if(request.getSession().getAttribute("savedUserType").equals("Director General")){
			ps=positionService.getPositionSatusByValue("active");
		}
		
		pos.setPositionstatus(ps);
		request.setAttribute("message", null);
		try {
			try {
				positionService.insert(pos);
				request.getSession().setAttribute("operationIsSuccesful", "yes");
			} catch (Exception e) {
				request.getSession().setAttribute("operationIsSuccesful", "no");
				HttpSession h = request.getSession();
				h.setAttribute("exceptionMessage",
						"Database error. Please make sure the submited data is correct and try again.");
				response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
			}
			for (User u : userService.getUserFindAll()) {
				if (u.getUsertype().getTitle().equals("Director General")) {
					sendMail(u.getEmail(), "Position opened",
							"Dear General Director, a new position has been created: "
									+ pos.getName()+"\t"+"Link Here:->"+link);
				}
			}
		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
	}

	public Position edit(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		int id = Integer.parseInt(request.getParameter("idPosition"));
		Position pos = positionService.getPositionById(id);
		String name = request.getParameter("name");
		int nrPersons = Integer.parseInt(request.getParameter("nrPersons"));
		pos.setName(name);
		pos.setNrPersons(nrPersons);
		Positionstatus ps = new Positionstatus();
		Positiondescription pd = new Positiondescription();
		pd.setIdPositionDescription(Integer.parseInt(request
				.getParameter("idDescription")));
		pos.setPositiondescription(pd);
		if (nrPersons > 0) {
			ps.setIdPositionStatus(441);

		} else {
			ps.setIdPositionStatus(442);
		}
		pos.setPositionstatus(ps);
		try {
			try {
				editDesc(request, response);
				positionService.update(pos);
				request.getSession()
						.setAttribute("operationIsSuccesful", "yes");
			} catch (Exception e) {
				request.getSession().setAttribute("operationIsSuccesful", "no");
				HttpSession h = request.getSession();
				h.setAttribute("exceptionMessage",
						"Database error. Please make sure the submited data is correct and try again.");
				response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
			}
			for (User u : userService.getUserFindAll()) {
				if (u.getIdUser() == pos.getIdUser()) {
					sendMail(
							u.getEmail(),
							"Position modified",
							"Dear " + u.getFirstName() + " " + u.getLastName()
									+ ", the position with id: "
									+ pos.getIdPosition() + " and name: "
									+ pos.getName() + " has been modified.");
				}
			}
		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
		return pos;
	}

	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String link = request.getRequestURL().toString();
		
		Position pos = edit(request, response);
		Positionstatus ps = new Positionstatus();
		ps.setIdPositionStatus(442);
		pos.setPositionstatus(ps);
		try {
			try {
				positionService.remove(pos);
				request.getSession().setAttribute("operationIsSuccesful", "yes");
			} catch (Exception e) {
				request.getSession().setAttribute("operationIsSuccesful", "no");
				HttpSession h = request.getSession();
				h.setAttribute("exceptionMessage",
						"Database error. Please make sure the submited data is correct and try again.");
				response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
			}
			for (User u : userService.getUserFindAll()) {
				if (u.getIdUser() == pos.getIdUser()) {
					sendMail(u.getEmail(), "Position disabled",  "Dear " + u.getFirstName()
							+ " " + u.getLastName()
							+ ", the position with id: " + pos.getIdPosition()
							+ " and name: " + pos.getName()
							+ " has been disabled."+"\t"+"Link Here:->"+link);
				}
			}
		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
	}

	public int addDesc(HttpServletRequest request, HttpServletResponse response) {
		Positiondescription posd = new Positiondescription();
		String requirements = request.getParameter("requirements");
		String responsabilities = request.getParameter("responsabilities");
		String project = request.getParameter("project");
		int id = Integer.parseInt(request.getParameter("department"));
		Department depa = dService.findDepartmentById(id);
		posd.setDepartment(depa);
		posd.setProject(project);
		posd.setRequirements(requirements);
		posd.setResponsabilities(responsabilities);
		posDescService.insert(posd);
		return posDescService.findPositiondescriptionByValues(posd);
	}

	public void editDesc(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		int id = Integer.parseInt(request.getParameter("idDescription"));
		String requirements = request.getParameter("requirements");
		String responsabilities = request.getParameter("responsabilities");
		String project = request.getParameter("project");
		Positiondescription posd = posDescService
				.findPositiondescriptionById(id);
		int idd = Integer.parseInt(request.getParameter("department"));
		Department dep = dService.findDepartmentById(idd);
		posd.setProject(project);
		posd.setRequirements(requirements);
		posd.setResponsabilities(responsabilities);
		posd.setDepartment(dep);
		try {
			posDescService.edit(posd);
		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
	}

	public void activate(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		Positionstatus ps = new Positionstatus();
		ps.setIdPositionStatus(441);
		int id = Integer.parseInt(request.getParameter("idPosition"));
		Position pos = positionService.getPositionById(id);
		pos.setPositionstatus(ps);
		if (id > 0) {
			pos.setIdPosition(id);
		}
		try {
			positionService.activate(pos);
			request.getSession().setAttribute("operationIsSuccesful", "yes");
		} catch (Exception e) {
			request.getSession().setAttribute("operationIsSuccesful", "no");
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
	}

	public void sendMail(String to, String subjectS, String bodyS) {

		String from = "javatrainingmsg@gmail.com";
		String subject = subjectS;
		String body = bodyS;
		Properties props = new Properties();
		props.put("mail.smtp.ssl.trust", "zmr.msg.de");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "zmr.msg.de");
		props.put("mail.smtp.port", "25");
		Authenticator auth = new SMTPAuthenticator();
		javax.mail.Session session = javax.mail.Session
				.getInstance(props, auth);
		javax.mail.Message msg1 = new MimeMessage(session);
		try {
			msg1.setFrom(new InternetAddress(from));
			msg1.setRecipients(javax.mail.Message.RecipientType.TO,
					InternetAddress.parse(to, false));
			msg1.setSubject(subject);
			msg1.setContent(body, "text/plain");
			Transport.send(msg1);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}

}
